<script>
import { Edit, Delete } from '@element-plus/icons-vue';
import crudMixin from '../../mixins/crudMixin';
import SearchBar from '../common/SearchBar.vue';
import BasePagination from '../common/BasePagination.vue';
import FormDialog from '../common/FormDialog.vue';
import TableActions from '../common/TableActions.vue';

export default {
  name: "Order",
  components: {
    SearchBar,
    BasePagination,
    FormDialog,
    TableActions
  },
  mixins: [crudMixin],
  data() {
    return {
      // 配置信息
      apiEndpoint: '/order',
      entityName: '订单',
      
      // 表单数据
      form: {
        id: '',
        memb_id: '',
        book_id: '',
        book_num: 1,
        order_date: '',
        consignee: '',
        area: '',
        street: '',
        cellphone: '',
        freight_fee: 0,
        deliv_mode: '普通快递',
        status: '待付款'
      },
      rules: {
        memb_id: [
          { required: true, message: '请选择会员ID', trigger: 'change' }
        ],
        book_id: [
          { required: true, message: '请输入图书ID', trigger: 'blur' }
        ],
        book_num: [
          { required: true, message: '请输入图书数量', trigger: 'blur' }
        ],
        consignee: [
          { required: true, message: '请输入收货人', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入地区', trigger: 'blur' }
        ],
        street: [
          { required: true, message: '请输入街道地址', trigger: 'blur' }
        ],
        cellphone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        freight_fee: [
          { required: true, message: '请输入运费', trigger: 'blur' }
        ],
        deliv_mode: [
          { required: true, message: '请选择配送方式', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择订单状态', trigger: 'change' }
        ]
      },
      memberList: [],
      statusOptions: ['待付款', '已付款', '已发货', '已完成', '已取消']
    };
  },
  computed: {
    // 表格操作按钮配置
    tableActions() {
      return (row) => [
        {
          type: 'primary',
          icon: 'Edit',
          tooltip: '编辑',
          handler: this.handleEdit,
          params: [row.index, row.row]
        },
        {
          type: 'danger',
          icon: 'Delete',
          tooltip: '删除',
          handler: this.handleDelete,
          params: [row.index, row.row]
        }
      ];
    }
  },
  async created() {
    await this.fetchMemberList();
    this.fetchData();
  },
  methods: {
    // 获取默认表单数据
    getDefaultForm() {
      return {
        id: '',
        memb_id: '',
        book_id: '',
        book_num: 1,
        order_date: '',
        consignee: '',
        area: '',
        street: '',
        cellphone: '',
        freight_fee: 0,
        deliv_mode: '普通快递',
        status: '待付款'
      };
    },
    
    // 重写删除ID获取方法
    getDeleteId(row) {
      return row.id;
    },
    
    // 重写编辑模式判断
    isEditMode(data) {
      return !!data.id;
    },
    // 获取会员列表
    fetchMemberList() {
      console.log('开始获取会员列表...');
      return axios.get('/member/all').then(response => {
        console.log('会员列表响应:', response);
        console.log('会员列表数据:', response.data);
        console.log('数据类型:', typeof response.data);
        console.log('是否为数组:', Array.isArray(response.data));
        
        this.memberList = response.data;
        console.log('设置后的memberList:', this.memberList);
        return response.data;
      }).catch(error => {
        console.error('获取会员列表失败:', error);
        console.error('错误详情:', error.response);
        this.$message.error('获取会员列表失败: ' + (error.response?.data?.message || error.message));
        return [];
      });
    },

    // 获取订单状态对应的类型
    getStatusType(status) {
      const statusMap = {
        '待付款': 'warning',
        '已付款': 'primary',
        '已发货': 'success',
        '已完成': 'success',
        '已取消': 'info'
      };
      return statusMap[status] || 'info';
    }
  }
}
</script>

<template>
  <div class="order-container">
    <!-- 搜索栏 -->
    <SearchBar
      title="订单管理"
      add-button-text="添加订单"
      placeholder="请输入关键词搜索..."
      v-model="searchForm.code"
      @add="handleAdd"
      @search="handleSearch"
    />

    <!-- 表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        element-loading-text="加载中..."
        :header-cell-style="{backgroundColor: '#f5f7fa', color: '#606266'}"
        highlight-current-row
        stripe
      >
        <el-table-column type="index" min-width="5%" align="center" label="序号"></el-table-column>
        <el-table-column prop="id" label="ID" min-width="5%" align="center"></el-table-column>
        <el-table-column prop="memb_id" label="会员ID" min-width="8%" align="center"></el-table-column>
        <el-table-column prop="book_id" label="图书ID" min-width="8%" align="center"></el-table-column>
        <el-table-column prop="book_num" label="图书数量" min-width="8%" align="center"></el-table-column>
        <el-table-column prop="order_date" label="订单日期" min-width="12%" align="center">
          <template #default="scope">
            {{ scope.row.order_date ? new Date(scope.row.order_date).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="consignee" label="收货人" min-width="8%" align="center"></el-table-column>
        <el-table-column prop="area" label="地区" min-width="10%" align="center"></el-table-column>
        <el-table-column prop="street" label="街道地址" min-width="12%" align="center"></el-table-column>
        <el-table-column prop="cellphone" label="手机号" min-width="10%" align="center"></el-table-column>
        <el-table-column prop="freight_fee" label="运费" min-width="8%" align="center">
          <template #default="scope">
            ¥{{ scope.row.freight_fee ? parseFloat(scope.row.freight_fee).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="deliv_mode" label="配送方式" min-width="8%" align="center"></el-table-column>
        <el-table-column prop="status" label="订单状态" min-width="8%" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="15%" align="center">
          <template #default="scope">
            <TableActions :actions="tableActions({ index: scope.$index, row: scope.row })" />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <BasePagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 添加/编辑对话框 -->
    <FormDialog
      :title="dialogTitle"
      v-model="dialogVisible"
      :form="form"
      :rules="rules"
      :loading="loading"
      width="550px"
      @submit="submitForm"
    >
      <template #default="{ form }">
          <el-form-item label="ID" prop="id" v-if="form.id">
            <el-input 
              v-model="form.id" 
              placeholder="系统自动生成"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="会员ID" prop="memb_id">
            <div style="margin-bottom: 8px; font-size: 12px; color: #666;">
              调试信息: 会员列表长度: {{ memberList.length }}, 数据: {{ JSON.stringify(memberList) }}
            </div>
            <el-select 
              v-model="form.memb_id" 
              placeholder="请选择会员ID" 
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in memberList"
                :key="item.id"
                :label="`${item.name} (ID: ${item.id})`"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图书ID" prop="book_id">
            <el-input 
              v-model="form.book_id" 
              placeholder="请输入图书ID"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="图书数量" prop="book_num">
            <el-input-number 
              v-model="form.book_num" 
              :min="1"
              placeholder="请输入图书数量"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="订单日期" prop="order_date">
            <el-date-picker
              v-model="form.order_date"
              type="datetime"
              placeholder="选择订单日期"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="收货人" prop="consignee">
            <el-input 
              v-model="form.consignee" 
              placeholder="请输入收货人姓名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="地区" prop="area">
            <el-input 
              v-model="form.area" 
              placeholder="请输入地区"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="街道地址" prop="street">
            <el-input 
              v-model="form.street" 
              placeholder="请输入街道地址"
              clearable
              type="textarea"
              :rows="2"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="cellphone">
            <el-input 
              v-model="form.cellphone" 
              placeholder="请输入手机号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="运费" prop="freight_fee">
            <el-input 
              v-model="form.freight_fee" 
              placeholder="请输入运费"
              clearable
            >
              <template #prefix>¥</template>
            </el-input>
          </el-form-item>
          <el-form-item label="配送方式" prop="deliv_mode">
            <el-select 
              v-model="form.deliv_mode" 
              placeholder="请选择配送方式" 
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in ['普通快递', '顺丰速运', '邮政EMS', '自提']"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单状态" prop="status">
            <el-select 
              v-model="form.status" 
              placeholder="请选择订单状态" 
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
      </template>
    </FormDialog>
  </div>
</template>

<style>
.order-container {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  overflow: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
  position: relative;
  padding-left: 12px;
}

.page-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #409EFF;
  border-radius: 2px;
}

.search {
  display: flex;
  gap: 10px;
  align-items: center;
}

.table-container {
  background-color: #fff;
  border-radius: 6px;
  padding: 10px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  flex: 1;
  overflow: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.custom-dialog .el-dialog__header {
  padding: 10px;
  margin: 0;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.custom-dialog .el-dialog__title {
  font-weight: 600;
  color: #303133;
  font-size: 18px;
}

.custom-dialog .el-dialog__body {
  padding: 20px 10px;
}

.custom-dialog .el-dialog__footer {
  padding: 10px;
  border-top: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}
</style>